package com.xliu.csopenproject.pim_server.image.meta.impl;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.xliu.csopenproject.pim_server.image.meta.ImageMetaData;
import com.xliu.csopenproject.pim_server.image.meta.ImageMetaReader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class ImageMetaReaderImpl implements ImageMetaReader {

    private final MetaDataTransform transform = MetaDataTransform.IMAGE_META_DATA_TRANSFORM;

    public ImageMetaData read(InputStream imageStream, String fileName, int fileSize) throws IOException {
        try {
            Metadata metadata = ImageMetadataReader.readMetadata(imageStream);
            ImageMetaData imageMetaData = getImageMetaData(metadata);

            imageMetaData.setFileName(fileName);
            imageMetaData.setFileSize(fileSize);

            return imageMetaData;
        } catch (ImageProcessingException e) {
            throw new IOException("process reading image input stream error", e);
        }
    }
    @Override
    public ImageMetaData read(String filePath) throws IOException {
        File imageFile = new File(filePath);

        try {
            Metadata metadata = ImageMetadataReader.readMetadata(imageFile);
            return getImageMetaData(metadata);
        } catch (ImageProcessingException e) {
            throw new IOException(String.format("process reading image file %s error", filePath), e);
        }
    }

    private ImageMetaData getImageMetaData(Metadata metadata) {
        Map<String, String> meta = new HashMap<>();

        for (Directory directory : metadata.getDirectories()) {
            if (directory == null) {
                continue;
            }
            for (Tag tag : directory.getTags()) {
                String tagName = tag.getTagName(); // 标签名
                String desc = tag.getDescription(); // 标签信息

                meta.put(tagName,desc);
            }
        }

        return transform.toImageMetaData(meta);
    }
}
